package com.littlec.sdk.manager;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.filter.MessageTypeFilter;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Packet;

import android.os.AsyncTask;
import android.text.TextUtils;
import android.util.Log;

import com.littlec.sdk.CMChatConfig;
import com.littlec.sdk.XMPPConnectionManager;
import com.littlec.sdk.asynctask.FileUploadPosAsyncTask;
import com.littlec.sdk.asynctask.GroupChatFileUploadAsyncTask;
import com.littlec.sdk.asynctask.GroupChatfFileUploadPosAsyncTask;
import com.littlec.sdk.entity.AckMessage;
import com.littlec.sdk.entity.CMMember;
import com.littlec.sdk.entity.CMMessage;
import com.littlec.sdk.entity.groupinfo.GroupInfo;
import com.littlec.sdk.entity.messagebody.AudioMessageBody;
import com.littlec.sdk.entity.messagebody.LocationMessageBody;
import com.littlec.sdk.entity.messagebody.MessageBody;
import com.littlec.sdk.entity.messagebody.RichTextMessageBody;
import com.littlec.sdk.entity.messagebody.SMSMessageBody;
import com.littlec.sdk.entity.messagebody.TextMessageBody;
import com.littlec.sdk.entity.messagebody.VoiceMailMessageBody;
import com.littlec.sdk.utils.CMChatGlobalStorage;
import com.littlec.sdk.utils.CMChatListener;
import com.littlec.sdk.utils.MyLogger;
import com.littlec.sdk.utils.SdkUtils;
import com.yinhai.constant.Contact;
import com.yinhai.constant.UrlConstant;
import com.yinhai.model.ContactsUser;
import com.yinhai.photo.utils.Photo;
import com.yinhai.util.RedioUtil;

public class CMMessageManager {
	private static final MyLogger logger = MyLogger
			.getLogger("CMMessageManager");
	private static CMMessageManager mInstance = null;
	private CMPacketListener cmPacketListener;
	private boolean done = false;
	private ExecutorService executorService = Executors.newFixedThreadPool(5);
	public Map<String, Chat> chats = new HashMap();

	public static CMMessageManager getInstance() {
		if (mInstance == null) {
			synchronized (CMMessageManager.class) {
				if (mInstance == null) {
					mInstance = new CMMessageManager();
				}
			}
		}
		return mInstance;
	}

	private synchronized boolean isResendMessageAllowed() {
		return !this.done;
	}

	public synchronized void stopResendMessage() {
		this.done = true;
	}

	public void release() {
		XMPPConnection conn = XMPPConnectionManager.getInstance()
				.getConnection();
		mInstance = null;
	}

	public void addMessageListener(
			CMChatListener.CMMessageReceivedCallBack messageCallBack) {
		if (messageCallBack == null)
			throw new NullPointerException();
		XMPPConnection connection = XMPPConnectionManager.getInstance()
				.getConnection();
		if (connection == null)
			return;
		connection.addPacketListener(new CMPacketListener(messageCallBack),
				new MessageTypeFilter(Message.Type.chat));
	}

	// 监听数据变化
	// PacketListener pListener = new PacketListener() {
	//
	// @Override
	// public void processPacket(Packet arg0) {
	// Message message = (Message) arg0;
	// Log.i("xxx", "dsafds");
	//
	// }
	// };

	public void sendMessage(CMMessage message,
			CMChatListener.CMCallBack callback) {
		String to = message.getTo();
		if ((callback == null) || (to == null)
				|| (message.getMessageBody().getContent() == null)) {
			throw new NullPointerException();
		}
		doSendMessage(message, callback);
	}

	private void doSendMessage(CMMessage message,
			CMChatListener.CallBack callback) {
		if (!checkChatType(message, callback)) {
			return;
		}
		logger.w("doSendMessage");
		switch (message.getContentType()) {
		case 0:
		case 3:
			// 发送单聊文本
		case 5:
			sendMessageText(message, callback);
			break;
		case 13:
			sendMessageRichText(message, callback);
			break;
		case 11:
			sendMessageATText(message, callback);
			break;
		case 8:
			sendMessageSMS(message, callback);
			break;
		case 2:
			// 发送语音
			sendMessageAudio(message, callback);
			break;
		case -1:
		case 1:
			// 发送图片
			sendMessagePic(message, callback);
			break;
		case 6:
			sendMessageFile(message, callback);
			break;
		case 4:
			sendMessageVideo(message, callback);
			break;
		case 9:
			sendMessageVoiceMail(message, callback);
			break;
		case 10:
			// 发送坐标位置
			sendMessageLocation(message, callback);
			break;
		case 7:
		case 12:
		}
	}

	// ��֤��Ϣ�ĺϷ���
	private boolean checkChatType(CMMessage message,
			CMChatListener.CallBack callback) {
		switch (message.getChatType()) {
		case 0:
			if (!SdkUtils.checkUserName(message.getTo())) {
				callback.onError(message, message.getTo() + ","
						+ "用户名不合法，请重新输入");
				return false;
			}

			break;
		case 1:
			if (TextUtils.isEmpty(message.getTo())) {
				callback.onError(message, "群ID不能为空");
				return false;
			}
			break;
		case 2:
			String[] array = message.getTo().split(" ");
			for (String username : array) {
				if (!SdkUtils.checkUserName(username)) {
					callback.onError(message, username + ",存在" + "用户名不合法，请重新输入");
					return false;
				}
			}
			break;
		default:
			callback.onError(message, "传入会话类型参数错误，共有单聊、群聊两种");
			return false;
		}
		return true;
	}

	private void sendMessageText(CMMessage message,
			CMChatListener.CallBack callback) {
		doSubmitMessageToExecutor(message, callback);
	}

	private void doSubmitMessageToExecutor(CMMessage message,
			CMChatListener.CallBack callback) {
		if (message.getChatType() == 0) {
			callback.onProgress(message, -1);
			sendChatMessage(message, callback);
			// 发送单聊消息
		} else if (message.getChatType() == 1) {
			callback.onProgress(message, -1);
			sendChatMessage(message, callback);
		} else if (message.getChatType() == 2) {
			callback.onProgress(message, -1);
			sendMutilChatMessage(message, callback);
		} else {
			callback.onError(message, "传入会话类型参数错误，共有单聊、群聊两种");
		}
	}

	private void sendChatMessage(final CMMessage message,
			final CMChatListener.CallBack callback) {
		this.executorService.submit(new Runnable() {
			public void run() {
				if (message.getChatType() == 0) {
					CMMessageManager.this.sendChatMessageInBackGround(message,
							callback, null, null);
				} else if (message.getChatType() == 1) {
					String groupId = message.getTo();
					String groupName = CMGroupManager.getInstance()
							.getGroupNamefromServer(groupId);
					message.setGroupInfo(new GroupInfo(groupId, groupName,
							CMChatGlobalStorage.getInstance()
									.getmLoginUserName()));
					ArrayList<CMMember> members = CMGroupManager.getInstance()
							.getGroupMembersfromServer(groupId);
					for (CMMember member : members) {
						if (!CMChatGlobalStorage.getInstance()
								.getmLoginUserName()
								.equals(member.getMemberId())) {
							message.setTo(member.getMemberId());
							CMMessageManager.this.sendChatMessageInBackGround(
									message, groupId, groupName);
						}
					}
				}

			}
		});
	}

	private void sendChatMessageInBackGround(CMMessage message,
			CMChatListener.CallBack callback, String groupId, String groupName) {
		// Message msg = composeMutilOrChatMessage(message);
		int tryTims = 15;
		while (isResendMessageAllowed()) {
			String to = message.getTo();
			Chat chat = (Chat) this.chats.get(to);
			XMPPConnection connection = XMPPConnectionManager.getInstance()
					.getConnection();
			if (connection == null) {
				callback.onError(message, "not connected");
				return;
			}
			if (chat == null) {
				chat = XMPPConnectionManager
						.getInstance()
						.getConnection()
						.getChatManager()
						.createChat(
								message.getTo()
										+ "@"
										+ XMPPConnectionManager.getInstance()
												.getConnection()
												.getServiceName(), null);

				this.chats.put(to, chat);
			}
			if ((connection.isConnected()) && (connection.isAuthenticated())) {
				try {
					XMPPConnectionManager.getInstance().sendOnlinePacket();
					// chat.sendMessage(msg);
					Message messageChat = new Message();
					// message.setProperty(IMMessage.KEY_TIME, time);
					messageChat.setProperty("type", Contact.TEXT);
					// // 个人聊天
					messageChat.setProperty("isGroup", "0");
					messageChat.setProperty("msgModelId", message.getUuid());

					// message.getSendName()=
					messageChat.setProperty("sendName", CMChatGlobalStorage
							.getInstance().getmLoginUserRealName());
					messageChat.setBody(message.getMessageBody().getContent());
					if (1 == message.getChatType()) {
						// 群组
						GroupInfo groupInfo = message.getGroupInfo();
						if (groupInfo != null) {
							messageChat.setProperty("groupID",
									groupInfo.getGroupId());
							messageChat.setProperty("groupName",
									groupInfo.getGroupName());
							// 群组聊天
							messageChat.setProperty("isGroup", "1");
						}

					}
					chat.sendMessage(messageChat);
					try {
						message.setProgress(100);
					} catch (Exception e) {
						e.printStackTrace();
					}
					try {
						callback.onSuccess(message);
					} catch (Exception e) {
						e.printStackTrace();
					}
					return;
				} catch (Exception e) {
					e.printStackTrace();
					if ((e.getMessage() != null)
							&& (e.getMessage().equals("recipient-unavailable"))) {
						callback.onError(message, "recipient-unavailable");
						return;
					}
				}

			}

			tryTims--;
			if (tryTims <= 0) {
				callback.onError(message, "消息报文发送失败");
				return;
			}

			try {
				logger.w("sendChatMessageInBackGround try sleep");
				Thread.sleep(20000L);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		callback.onError(message, "not connected");
	}

	private void sendChatMessageInBackGround(CMMessage message, String groupId,
			String groupName) {
		// Message msg = composeMutilOrChatMessage(message);
		int tryTims = 15;
		while (isResendMessageAllowed()) {
			String to = message.getTo();
			Chat chat = (Chat) this.chats.get(to);
			XMPPConnection connection = XMPPConnectionManager.getInstance()
					.getConnection();
			if (connection == null) {
				return;
			}
			if (chat == null) {
				chat = XMPPConnectionManager
						.getInstance()
						.getConnection()
						.getChatManager()
						.createChat(
								message.getTo()
										+ "@"
										+ XMPPConnectionManager.getInstance()
												.getConnection()
												.getServiceName(), null);

				this.chats.put(to, chat);
			}
			if ((connection.isConnected()) && (connection.isAuthenticated())) {
				try {
					XMPPConnectionManager.getInstance().sendOnlinePacket();
					// chat.sendMessage(msg);
					Message messageChat = new Message();
					// message.setProperty(IMMessage.KEY_TIME, time);
					messageChat.setProperty("type", Contact.TEXT);
					// // 个人聊天
					messageChat.setProperty("isGroup", "1");
					messageChat.setProperty("msgModelId", message.getUuid());

					// message.getSendName()=
					messageChat.setProperty("sendName", CMChatGlobalStorage
							.getInstance().getmLoginUserRealName());
					messageChat.setBody(message.getMessageBody().getContent());
					if (1 == message.getChatType()) {
						// 群组
						GroupInfo groupInfo = message.getGroupInfo();
						if (groupInfo != null) {
							messageChat.setProperty("groupID",
									groupInfo.getGroupId());
							messageChat.setProperty("groupName",
									groupInfo.getGroupName());
							// 群组聊天
							messageChat.setProperty("isGroup", "1");
						}

					}
					chat.sendMessage(messageChat);
					try {
						message.setProgress(100);
					} catch (Exception e) {
						e.printStackTrace();
					}
					return;
				} catch (Exception e) {
					e.printStackTrace();
					if ((e.getMessage() != null)
							&& (e.getMessage().equals("recipient-unavailable"))) {
						return;
					}
				}

			}

			tryTims--;
			if (tryTims <= 0) {
				return;
			}

			try {
				logger.w("sendChatMessageInBackGround try sleep");
				Thread.sleep(20000L);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	private Message composeMutilOrChatMessage(CMMessage message) {
		Message msg;
		if (message.getChatType() == 2) {
			msg = new Message(CMChatConfig.ServerConfig.xmppServiceName,
					Message.Type.chat);
		} else {
			// 单聊
			msg = new Message(null, Message.Type.chat);
		}

		message.setPacketId(msg.getPacketID());
		MessageBody messageBody = message.getMessageBody();
		if ((messageBody instanceof TextMessageBody)) {
			msg.setBody(((TextMessageBody) message.getMessageBody())
					.getMessageContent());
		} else if ((messageBody instanceof SMSMessageBody)) {
			String text = message.getMessageBody().getContent();
			msg.setBody(text);
		} else if ((messageBody instanceof VoiceMailMessageBody)) {
			msg.setBody("file msg");
		} else if ((messageBody instanceof LocationMessageBody)) {
			msg.setBody("location msg");
		} else if ((messageBody instanceof RichTextMessageBody)) {
		} else {
		}

		return msg;
	}

	private void sendGroupChatMessage(final CMMessage message,
			final CMChatListener.CallBack callback) {
		this.executorService.submit(new Runnable() {
			public void run() {
				CMMessageManager.this.sendGroupChatMessageInBackGround(message,
						callback);
			}
		});
	}

	private void sendGroupChatMessageInBackGround(CMMessage message,
			CMChatListener.CallBack callback) {

	}

	private void sendMutilChatMessage(final CMMessage message,
			final CMChatListener.CallBack callback) {
		this.executorService.submit(new Runnable() {
			public void run() {
				CMMessageManager.this.sendMutilChatMessageInBackGround(message,
						callback);
			}
		});
	}

	private void sendMutilChatMessageInBackGround(CMMessage message,
			CMChatListener.CallBack callback) {

	}

	private void sendMessageRichText(CMMessage message,
			CMChatListener.CallBack callback) {
		RichTextMessageBody messageBody = (RichTextMessageBody) message
				.getMessageBody();
		if ((messageBody.getTitle() == null)
				|| (messageBody.getWebSite() == null)) {
			throw new NullPointerException();
		}
		doSubmitMessageToExecutor(message, callback);
	}

	private void sendMessageATText(CMMessage message,
			CMChatListener.CallBack callback) {
		if (message.getChatType() == 1) {
			callback.onProgress(message, -1);
			sendGroupChatMessage(message, callback);
		} else {
			callback.onError(message, "传入会话类型参数错误，仅能为群聊");
		}
	}

	private void sendMessageSMS(CMMessage message,
			CMChatListener.CallBack callback) {
		String text = message.getMessageBody().getContent();
		if (text.length() > 1000) {
			throw new IllegalArgumentException("发送短信文本字数太长，最多1000字");
		}
		if (message.getChatType() == 0) {
			callback.onProgress(message, -1);
			sendChatMessage(message, callback);
		} else if (message.getChatType() == 2) {
			callback.onProgress(message, -1);
			sendMutilChatMessage(message, callback);
		} else {
			callback.onError(message, "传入会话类型参数错误，仅能传入单聊");
		}
	}

	public void doSendChatMessageAudio(final CMMessage message,
			CMChatListener.CallBack callback) {
		if (isValidChatType(message.getChatType())) {
			String filePath = message.getMessageBody().getContent();
			File file = new File(filePath);
			if (!file.exists()) {
				callback.onError(message, "文件不存在");
				return;
			}
			if (file.length() <= 0L) {
				callback.onError(message, "文件内容不能为空");
				return;
			}
			if (file.length() >= 10485760L) {
				callback.onError(message, "文件超过10M");
				return;
			}
			String radioContent = "";
			if (checkFileformat(2, filePath)) {

				try {
					radioContent = RedioUtil.fileToString(filePath);
				} catch (IOException e) {
					e.printStackTrace();
					callback.onError(message, "转换异常");
				}
				Message messageChat = new Message();
				// message.setProperty(IMMessage.KEY_TIME, time);
				messageChat.setProperty("type", Contact.REDIO);
				messageChat.setProperty("isGroup", "0");
				messageChat.setProperty("msgModelId", message.getUuid());

				messageChat.setProperty("second", ((AudioMessageBody) message
						.getMessageBody()).getDuration());

				messageChat.setProperty("sendName", CMChatGlobalStorage
						.getInstance().getmLoginUserRealName());
				messageChat.setBody(radioContent);
				String to = message.getTo();
				Chat chat = (Chat) this.chats.get(to);
				XMPPConnection connection = XMPPConnectionManager.getInstance()
						.getConnection();
				if (connection == null) {
					callback.onError(message, "not connected");
					return;
				}
				if (chat == null) {
					chat = XMPPConnectionManager
							.getInstance()
							.getConnection()
							.getChatManager()
							.createChat(
									message.getTo()
											+ "@"
											+ XMPPConnectionManager
													.getInstance()
													.getConnection()
													.getServiceName(), null);

					this.chats.put(to, chat);
				}
				if ((connection.isConnected())
						&& (connection.isAuthenticated())) {
					try {
						XMPPConnectionManager.getInstance().sendOnlinePacket();
						chat.sendMessage(messageChat);
						try {
							message.setProgress(100);
						} catch (Exception e) {
							e.printStackTrace();
						}
						try {
							callback.onSuccess(message);
						} catch (Exception e) {
							e.printStackTrace();
						}
						return;
					} catch (Exception e) {
						e.printStackTrace();
						if ((e.getMessage() != null)
								&& (e.getMessage()
										.equals("recipient-unavailable"))) {
							callback.onError(message, "recipient-unavailable");
							return;
						}
					}
				}
			} else {
				callback.onError(message, "文件类型错误，目前支持mp3、amr格式语音");
			}
		} else {
			callback.onError(message, "传入会话类型参数错误，共有单聊、群聊两种");
		}
	}

	public void doSendChatMessageAudio(final CMMessage message) {
		String groupId = message.getTo();
		if (isValidChatType(message.getChatType())) {
			String groupName = CMGroupManager.getInstance()
					.getGroupNamefromServer(groupId);
			String filePath = message.getMessageBody().getContent();
			File file = new File(filePath);
			String radioContent = "";
			if (checkFileformat(2, filePath)) {

				try {
					radioContent = RedioUtil.fileToString(filePath);
				} catch (IOException e) {
					e.printStackTrace();
				}
				List<CMMember> members = CMGroupManager.getInstance()
						.getGroupMembersfromServer(groupId);
				for (CMMember member : members) {
					if (CMChatGlobalStorage.getInstance().getmLoginUserName()
							.equals(member.getMemberId())) {
						Message messageChat = new Message();
						// message.setProperty(IMMessage.KEY_TIME, time);
						messageChat.setProperty("type", Contact.REDIO);
						messageChat.setProperty("isGroup", "1");
						messageChat
								.setProperty("msgModelId", message.getUuid());

						messageChat.setProperty("second",
								((AudioMessageBody) message.getMessageBody())
										.getDuration());
						messageChat.setProperty("groupID", groupId);
						messageChat.setProperty("groupName", groupName);
						// 群组聊天
						messageChat.setProperty("isGroup", "1");
						messageChat.setProperty("sendName", CMChatGlobalStorage
								.getInstance().getmLoginUserRealName());
						messageChat.setBody(radioContent);
						String to = member.getMemberId();
						Chat chat = (Chat) this.chats.get(to);
						XMPPConnection connection = XMPPConnectionManager
								.getInstance().getConnection();
						if (connection == null) {
							return;
						}
						if (chat == null) {
							chat = XMPPConnectionManager
									.getInstance()
									.getConnection()
									.getChatManager()
									.createChat(
											message.getTo()
													+ "@"
													+ XMPPConnectionManager
															.getInstance()
															.getConnection()
															.getServiceName(),
											null);

							this.chats.put(to, chat);
						}
						if ((connection.isConnected())
								&& (connection.isAuthenticated())) {
							try {
								XMPPConnectionManager.getInstance()
										.sendOnlinePacket();
								chat.sendMessage(messageChat);
								try {
									message.setProgress(100);
								} catch (Exception e) {
									e.printStackTrace();
								}
								return;
							} catch (Exception e) {
								e.printStackTrace();
								if ((e.getMessage() != null)
										&& (e.getMessage()
												.equals("recipient-unavailable"))) {
									return;
								}
							}
						}
					}
				}
			} else {
			}
		} else {
		}
	}

	private void sendMessageAudio(final CMMessage message,
			final CMChatListener.CallBack callback) {
		this.executorService.submit(new Runnable() {
			public void run() {
				if (message.getChatType() == 0) {
					callback.onProgress(message, -1);
					doSendChatMessageAudio(message, callback);
					// 发送单聊消息
				} else if (message.getChatType() == 1) {
					callback.onProgress(message, -1);
					doSendChatMessageAudio(message);
				}
			}
		});

	}

	private boolean isValidChatType(int chatType) {
		if ((chatType == 0) || (chatType == 1) || (chatType == 2)) {
			return true;
		}
		return false;
	}

	private boolean checkFileformat(int fileMode, String filePath) {
		filePath = filePath.toLowerCase();
		switch (fileMode) {
		case 1:
			if ((filePath.endsWith(".jpg")) || (filePath.endsWith(".jpeg"))
					|| (filePath.endsWith(".png"))
					|| (filePath.endsWith(".bmp"))
					|| (filePath.endsWith(".gif"))) {
				return true;
			}
			break;
		case 2:
			if ((filePath.endsWith(".mp3")) || (filePath.endsWith(".amr"))) {
				return true;
			}
			break;
		case 4:
			if ((filePath.endsWith(".rmvb")) || (filePath.endsWith(".avi"))
					|| (filePath.endsWith(".rm"))
					|| (filePath.endsWith(".mpg"))
					|| (filePath.endsWith(".mpeg"))
					|| (filePath.endsWith(".mov"))
					|| (filePath.endsWith(".wmv"))
					|| (filePath.endsWith(".asf"))
					|| (filePath.endsWith(".dat"))
					|| (filePath.endsWith(".asx"))
					|| (filePath.endsWith(".mp4"))
					|| (filePath.endsWith(".3gp"))) {
				return true;
			}
			break;
		case 6:
			if ((filePath.endsWith(".bmp")) || (filePath.endsWith(".gif"))
					|| (filePath.endsWith(".jpeg"))
					|| (filePath.endsWith(".jpeg2000"))
					|| (filePath.endsWith(".jp2"))
					|| (filePath.endsWith(".tiff"))
					|| (filePath.endsWith(".psd"))
					|| (filePath.endsWith(".png"))
					|| (filePath.endsWith(".svg"))
					|| (filePath.endsWith(".pcx"))
					|| (filePath.endsWith(".dxf"))
					|| (filePath.endsWith(".wmf"))
					|| (filePath.endsWith(".emf"))
					|| (filePath.endsWith(".lic"))
					|| (filePath.endsWith(".fli"))
					|| (filePath.endsWith(".flc"))
					|| (filePath.endsWith(".eps"))
					|| (filePath.endsWith(".tga"))
					|| (filePath.endsWith(".jpg"))
					|| (filePath.endsWith(".wma"))
					|| (filePath.endsWith(".mp3"))
					|| (filePath.endsWith(".wav"))
					|| (filePath.endsWith(".mid"))
					|| (filePath.endsWith(".mp1"))
					|| (filePath.endsWith(".mp2"))
					|| (filePath.endsWith(".amr"))
					|| (filePath.endsWith(".wma"))
					|| (filePath.endsWith(".m4a"))
					|| (filePath.endsWith(".aac"))
					|| (filePath.endsWith(".rmvb"))
					|| (filePath.endsWith(".avi"))
					|| (filePath.endsWith(".rm"))
					|| (filePath.endsWith(".mpg"))
					|| (filePath.endsWith(".mpeg"))
					|| (filePath.endsWith(".mov"))
					|| (filePath.endsWith(".wmv"))
					|| (filePath.endsWith(".asf"))
					|| (filePath.endsWith(".dat"))
					|| (filePath.endsWith(".asx"))
					|| (filePath.endsWith(".wvx"))
					|| (filePath.endsWith(".mpe"))
					|| (filePath.endsWith(".mpa"))
					|| (filePath.endsWith(".mp4"))
					|| (filePath.endsWith(".3gp"))
					|| (filePath.endsWith(".apk"))
					|| (filePath.endsWith(".ipa"))
					|| (filePath.endsWith(".doc"))
					|| (filePath.endsWith(".docx"))
					|| (filePath.endsWith(".ppt"))
					|| (filePath.endsWith(".pptx"))
					|| (filePath.endsWith(".xls"))
					|| (filePath.endsWith(".xlsx"))
					|| (filePath.endsWith(".txt"))
					|| (filePath.endsWith(".plist"))
					|| (filePath.endsWith(".vcf")))
				return true;
			break;
		case 3:
		case 5:
		}
		return false;
	}

	private class FileUploadAsyncTask extends AsyncTask<File, Integer, Boolean> {
		private long totalSize;
		private CMMessage message;
		private CMChatListener.CallBack callback;
		private String resultJson;

		public FileUploadAsyncTask(CMMessage message,
				CMChatListener.CallBack callback) {
			this.message = message;
			this.callback = callback;
		}

		protected void onPreExecute() {
			CMMessageManager.logger.i("onPreExecute");
			this.callback.onProgress(this.message, -1);
		}

		protected Boolean doInBackground(File[] params) {
			HttpClient httpclient = new DefaultHttpClient();
			HttpPost post3 = new HttpPost(UrlConstant.LOCAL_URI
					+ "addPhoto?phone=" + message.getUuid());
			File upfile = params[0];
			MultipartEntity entity3 = new MultipartEntity();
			try {
				entity3.addPart("oicon", new FileBody(upfile));
				post3.setEntity(entity3);
				HttpResponse rsp = httpclient.execute(post3);
				HttpEntity entity = rsp.getEntity();
				if (entity != null) {
					entity.consumeContent();
				}
			} catch (Exception e1) {
				e1.printStackTrace();
			}
			return Boolean.valueOf(true);
		}

		protected void onProgressUpdate(Integer[] integer) {
			int progress = integer[0].intValue();
			if (progress != this.message.getProgress()) {
				this.message.setProgress(progress);
				try {
					this.callback.onProgress(this.message, progress);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}

		protected void onPostExecute(Boolean result) {
			if (result.booleanValue()) {
				try {
					String to = message.getTo();
					Chat chat = (Chat) CMMessageManager.getInstance().chats
							.get(to);
					XMPPConnection connection = XMPPConnectionManager
							.getInstance().getConnection();
					if (connection == null) {
						callback.onError(message, "not connected");
						return;
					}
					if (chat == null) {
						chat = XMPPConnectionManager
								.getInstance()
								.getConnection()
								.getChatManager()
								.createChat(
										message.getTo()
												+ "@"
												+ XMPPConnectionManager
														.getInstance()
														.getConnection()
														.getServiceName(), null);

						CMMessageManager.getInstance().chats.put(to, chat);
					}
					if ((connection.isConnected())
							&& (connection.isAuthenticated())) {
						try {
							XMPPConnectionManager.getInstance()
									.sendOnlinePacket();
							Message messageChat = new Message();
							messageChat.setProperty("type", Contact.PHOTO);
							messageChat.setProperty("isGroup", "0");
							messageChat.setProperty("msgModelId",
									message.getUuid());

							messageChat.setProperty("sendName",
									CMChatGlobalStorage.getInstance()
											.getmLoginUserRealName());
							messageChat.setBody(message.getUuid());
							chat.sendMessage(messageChat);
							try {
								message.setProgress(100);
							} catch (Exception e) {
								e.printStackTrace();
							}
							try {
								callback.onSuccess(message);
							} catch (Exception e) {
								e.printStackTrace();
							}
							return;
						} catch (Exception e) {
							e.printStackTrace();
							if ((e.getMessage() != null)
									&& (e.getMessage()
											.equals("recipient-unavailable"))) {
								callback.onError(message,
										"recipient-unavailable");
								return;
							}
						}

					}
				} catch (Exception e) {
					e.printStackTrace();
					this.callback.onError(this.message, "文件上传失败");
				}
			} else
				this.callback.onError(this.message, "文件上传失败");
		}

	}

	public void doSendChatMessagePic(final CMMessage message,
			CMChatListener.CallBack callback) {
		String filePath = message.getMessageBody().getContent();
		if (checkFileEmpty(filePath)) {
			callback.onError(message, "传入文件路径不能为空");
			return;
		}
		if (checkFileformat(1, filePath)) {
			File file = new File(filePath);
			if (!file.exists()) {
				callback.onError(message, "文件不存在");
				return;
			}
			if (file.length() <= 0L) {
				callback.onError(message, "文件内容不能为空");
				return;
			}
			if (file.length() >= 10485760L) {
				callback.onError(message, "文件超过10M");
				return;
			}
			FileUploadAsyncTask fileUploadAsyncTask = new FileUploadAsyncTask(
					message, callback);
			fileUploadAsyncTask.executeOnExecutor(this.executorService,
					new File[] { file });
		} else {
			callback.onError(message, "传入图片文件格式错误，目前支持jpg、jpeg、png、bmp、gif格式");
		}
	}

	public void doSendChatMessagePic(final CMMessage message) {
		String filePath = message.getMessageBody().getContent();
		if (checkFileEmpty(filePath)) {
			return;
		}
		if (checkFileformat(1, filePath)) {
			File file = new File(filePath);
			if (!file.exists()) {
				return;
			}
			if (file.length() <= 0L) {
				return;
			}
			if (file.length() >= 10485760L) {
				return;
			}
			GroupChatFileUploadAsyncTask fileUploadAsyncTask = new GroupChatFileUploadAsyncTask(
					message);
			fileUploadAsyncTask.executeOnExecutor(this.executorService,
					new File[] { file });
		} else {
		}
	}

	private void sendMessagePic(final CMMessage message,
			final CMChatListener.CallBack callback) {
		this.executorService.submit(new Runnable() {
			public void run() {
				if (isValidChatType(message.getChatType())) {
					if (message.getChatType() == 0) {
						callback.onProgress(message, -1);
						doSendChatMessagePic(message, callback);
						// 发送单聊消息
					} else if (message.getChatType() == 1) {
						callback.onProgress(message, -1);
						doSendChatMessagePic(message);
					}

				} else {
					callback.onError(message, "传入会话类型参数错误，共有单聊、群聊两种");
				}
			}
		});
	}

	private boolean checkFileEmpty(String filePath) {
		return (TextUtils.isEmpty(filePath)) || (filePath.equals("/"));
	}

	private void sendMessageFile(CMMessage message,
			CMChatListener.CallBack callback) {

	}

	private void sendMessageVideo(CMMessage message,
			CMChatListener.CallBack callback) {

	}

	private void sendMessageVoiceMail(CMMessage message,
			CMChatListener.CallBack callback) {

	}

	private void doSendChatMessageLocation(final CMMessage message,
			CMChatListener.CallBack callBack) {
		LocationMessageBody messageBody = (LocationMessageBody) message
				.getMessageBody();
		String filePath = Photo.getSaveIMPicPath() + messageBody.getFileName();
		if (checkFileEmpty(filePath)) {
			callBack.onError(message, "传入文件路径不能为空");
			return;
		}
		String address = messageBody.getAddress();
		double longtitudu = messageBody.getLongitude();
		double latitude = messageBody.getLatitude();
		if ((longtitudu < -180.0D) || (longtitudu > 180.0D)
				|| (latitude < -90.0D) || (latitude > 90.0D)) {
			callBack.onError(message, "经纬度输入错误，纬度介于-90~90，经度介于-180~180");
			return;
		}
		if (address == null) {
			callBack.onError(message, "位置地址描述不能为空");
			return;
		}
		if (checkFileformat(1, filePath)) {
			File file = new File(filePath);
			if (!file.exists()) {
				callBack.onError(message, "文件不存在");
				return;
			}
			if (file.length() <= 0L) {
				callBack.onError(message, "文件内容不能为空");
				return;
			}
			if (file.length() >= 10485760L) {
				callBack.onError(message, "文件超过10M");
				return;
			}

			FileUploadPosAsyncTask fileUploadAsyncTask = new FileUploadPosAsyncTask(
					message, callBack);
			fileUploadAsyncTask.executeOnExecutor(this.executorService,
					new File[] { file });
		} else {
			callBack.onError(message, "传入图片文件格式错误，目前支持jpg、jpeg、png、bmp、gif格式");
		}
	}
	private void doSendChatMessageLocation(final CMMessage message) {
		LocationMessageBody messageBody = (LocationMessageBody) message
				.getMessageBody();
		String filePath = Photo.getSaveIMPicPath() + messageBody.getFileName();
		if (checkFileEmpty(filePath)) {
			return;
		}
		String address = messageBody.getAddress();
		double longtitudu = messageBody.getLongitude();
		double latitude = messageBody.getLatitude();
		if ((longtitudu < -180.0D) || (longtitudu > 180.0D)
				|| (latitude < -90.0D) || (latitude > 90.0D)) {
			return;
		}
		if (address == null) {
			return;
		}
		if (checkFileformat(1, filePath)) {
			File file = new File(filePath);
			if (!file.exists()) {
				return;
			}
			if (file.length() <= 0L) {
				return;
			}
			if (file.length() >= 10485760L) {
				return;
			}

			GroupChatfFileUploadPosAsyncTask fileUploadAsyncTask = new GroupChatfFileUploadPosAsyncTask(message);
			fileUploadAsyncTask.executeOnExecutor(this.executorService,
					new File[] { file });
		} else {
		}
	}
	

	private void sendMessageLocation(final CMMessage message,
			final CMChatListener.CallBack callBack) {
		this.executorService.submit(new Runnable() {
			public void run() {
				if (isValidChatType(message.getChatType())) {
					if (message.getChatType() == 0) {
						callBack.onProgress(message, -1);
						doSendChatMessageLocation(message, callBack);
						// 发送单聊消息
					} else if (message.getChatType() == 1) {
						callBack.onProgress(message, -1);
						doSendChatMessageLocation(message);
					}
				} else {
					callBack.onError(message, "传入会话类型参数错误，共有单聊、群聊两种");
				}
			}
		});
	}

	public void sendMessage(final AckMessage ackMessage,
			final CMChatListener.OnCMListener callback) {
		if (ackMessage == null) {
			throw new NullPointerException();
		}
		if (!SdkUtils.checkUserName(ackMessage.getTo())) {
			callback.onFailed(ackMessage.getTo() + "," + "用户名不合法，请重新输入");
			return;
		}

		final Message msg = new Message(null, Message.Type.chat);
		this.executorService.submit(new Runnable() {
			public void run() {
				doSendMessage(ackMessage, callback);
			}
		});
	}

	private void doSendMessage(final AckMessage ackMessage,
			final CMChatListener.OnCMListener callback) {
		XMPPConnection conn = XMPPConnectionManager.getInstance()
				.getConnection();
		String to = ackMessage.getTo();
		Chat chat = (Chat) this.chats.get(to);
		XMPPConnection connection = XMPPConnectionManager.getInstance()
				.getConnection();
		if (connection == null) {
			return;
		}
		if (chat == null) {
			chat = XMPPConnectionManager
					.getInstance()
					.getConnection()
					.getChatManager()
					.createChat(
							ackMessage.getTo()
									+ "@"
									+ XMPPConnectionManager.getInstance()
											.getConnection().getServiceName(),
							null);

			this.chats.put(to, chat);
		}
		if ((connection.isConnected()) && (connection.isAuthenticated())) {
			try {
				XMPPConnectionManager.getInstance().sendOnlinePacket();
				Message messageChat = new Message();
				messageChat.setProperty("msgModelId",
						ackMessage.getMessageUuid());
				messageChat.setProperty("isAnswer", "1");
				messageChat.setBody("22");
				chat.sendMessage(messageChat);
				return;
			} catch (Exception e) {
				e.printStackTrace();
				if ((e.getMessage() != null)
						&& (e.getMessage().equals("recipient-unavailable"))) {
					return;
				}
			}

		}
	}
}
